package com.glory.dgcpcpda.activity.mfg;


import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.EdcSetBinAdapter;
import com.glory.dgcpcpda.adapter.LastBatchAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.EdcEntity;
import com.glory.dgcpcpda.entity.EdcSetBinEntity;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.EquipMentEntity;
import com.glory.dgcpcpda.entity.EywEqpWorkEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class EQCOffLineDataSortActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqcNum)
    FreeUI_ClearEditText etEqcNum;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.tvScarpNum)
    TextView tvScarpNum;
    @BindView(R.id.tvTotal)
    TextView tvTotal;
    @BindView(R.id.tvGetData)
    TextView tvGetData;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvBINInfoList)
    RecyclerView rvBINInfoList;
    @BindView(R.id.rvLastBatchList)
    RecyclerView rvLastBatchList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llScarpNum)
    LinearLayout llScarpNum;
    @BindView(R.id.llSampleQty)
    LinearLayout llSampleQty;
    @BindView(R.id.llEqcNum)
    LinearLayout llEqcNum;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvSampleQty)
    TextView tvSampleQty;
    private EdcSetBinAdapter edcSetBinAdapter;
    private EdcEntity body;
    private LastBatchAdapter lastBatchAdapter;
    private String customercode = "";


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ft_off_line_data_sort;
    }

    @Override
    protected void initView() {
        listTv1.setText("采集名称");
        listTv2.setText("采集描述");
        listTv3.setText("值");
        listTv4.setText("占比良率");
        llScarpNum.setVisibility(View.GONE);
        llSampleQty.setVisibility(View.GONE);
        tvGetData.setVisibility(View.GONE);
        llEqcNum.setVisibility(View.VISIBLE);
        initRecyclerView(rvBINInfoList,this);
        initRecyclerView(rvLastBatchList,this);
        tvTitle.setText("EQC整合");
        setMainLayout(llMain);
        edcSetBinAdapter = new EdcSetBinAdapter(null);
        edcSetBinAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        edcSetBinAdapter.isFirstOnly(false);
        rvBINInfoList.setAdapter(edcSetBinAdapter);
        lastBatchAdapter = new LastBatchAdapter(null);
        lastBatchAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        lastBatchAdapter.isFirstOnly(false);
        rvLastBatchList.setAdapter(lastBatchAdapter);
        initEdit(etLot, s -> LotUtils.searchLotInfo(EQCOffLineDataSortActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                customercode = response.getLOT().getCUSTOMERCODE();
                tvNum.setText(response.getLOT().getMAINQTY());
                edcSetBinAdapter.setMainqty(Integer.parseInt(response.getLOT().getMAINQTY()));
                tvStep.setText(response.getLOT().getSTEPNAME() + "/" + response.getLOT().getSTEPDESC());
                String state = response.getLOT().getSTATE();
                if(state.equals("正在作业")){
                    state = state + " - " + response.getLOT().getEQUIPMENTID();
                }
                tvLotState.setText(state);
                String eqpid=response.getLOT().getEQUIPMENTID();
                requestEdcData();
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"LOTQUERY");
            }
        }));

    }

    private void requestEdcData() {
        FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                (new TypeToken<BaseResponseBean<EdcEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    body = response.body().getResponse().getBody();
                    lastBatchAdapter.setNewData(body.getLOTLIST());
                    tvScarpNum.setText(String.valueOf(body.getDAWBQTY()));
                    tvTotal.setText(String.valueOf(body.getTOTALQTY()));
                    tvSampleQty.setText(String.valueOf(body.getSAMPLEQTY()));
                    if (body.getEDCSETLIST().size() <= 0){
                        showToast("BIN列表为空",false);
                        return;
                    }

                    if (body.getEDCSETLIST().get(0).getEDCTYPE().equals("BIN")){
                        List<EdcSetBinEntity> binData = new ArrayList<>();
                        for (EdcSetBinEntity entity : body.getEDCSETLIST().get(0).getEDCSETITEMLINELIST()){
                            if (entity.getBINTYPE().equals("G")){
                                continue;
                            }
                            binData.add(entity);
                        }

                        ArrayList<Double> strings = new ArrayList<>();

                        for(EdcSetBinEntity entry : binData){
                            String[] ns = entry.getNAME().split("N");
                            String binName = "";
                            if (ns[1].contains("_")){
                                binName = ns[1].replace("_",".");
                            }else{
                                binName = ns[1];
                            }

                            strings.add(Double.parseDouble(binName));
                            entry.setCODE(Double.parseDouble(binName));
                        }
                        Collections.sort(strings);
                        List<EdcSetBinEntity> entityList = new ArrayList<>();
                        for (Double s:strings) {
                            for (EdcSetBinEntity sm:binData) {
                                if (sm.getNAME().equals("BIN11")){
                                    sm.setVALUE(String.valueOf(body.getSAMPLEQTY()));
                                }
                                if (s == sm.getCODE()){
                                    entityList.add(sm);
                                }
                            }
                        }


                        edcSetBinAdapter.setNewData(entityList);

                    }else {
                        showConfirmDialog(EQCOffLineDataSortActivity.this,"只支持BIN数据类型采集");
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"CPCGETEDCCURRENT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOTID",getText(etLot));
        NetUtils.requestPostNet("CPC.CPCGETEDCCURRENT","TRANSFERMES",this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvTempSave,R.id.tvSave,R.id.tvGetData,R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvTempSave:
                submit(true);
                break;
            case R.id.tvSave:
            case R.id.tvBaseSubmit:
                int sum = 0;
                for (EdcSetBinEntity entity : edcSetBinAdapter.getData()){
                    if (!entity.getVALUE().equals("") && !entity.getNAME().equals("BIN99")){
                        sum += Integer.parseInt(entity.getVALUE());
                    }
                }

                int lotNum = Integer.parseInt(etEqcNum.getText().toString().equals("")?"0":etEqcNum.getText().toString());

                if (sum != lotNum){
                    showConfirmDialog("Total不等于BIN的总数！差值：" + (lotNum - sum));
                    return;
                }

                submit(false);
                break;
        }
    }

    private void synchronous(int position) {
        List<EdcSetBinEntity> data = edcSetBinAdapter.getData();
        //修改BIN2得数量
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getNAME().equals("BIN2")){
                EdcSetBinEntity entity = data.get(i);
                String value = entity.getVALUE();
                entity.setVALUE(String.valueOf(Integer.parseInt(value.equals("") ? "0" : value) - body.getDAWBQTY()));
                break;
            }
        }
        //修改BIN99得数量
        edcSetBinAdapter.getData().get(position).setVALUE(String.valueOf(body.getDAWBQTY()));
        edcSetBinAdapter.notifyDataSetChanged();
        showToast("同步成功",true);
        tvGetData.setVisibility(View.GONE);
    }

    private void submit(boolean isTemp) {

        showSubmitDialog(new onSubmitListener() {
            @Override
            public void setOnSubmitListener() {

                FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                        (new TypeToken<BaseResponseBean<EdcEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                            showConfirmDialog(EQCOffLineDataSortActivity.this,"提交成功");
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"CPCGETEDCCURRENT");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("LOTID",getText(etLot));
                map.addProperty("ISTEMP",isTemp);
                map.addProperty("ISRMS",false);
                map.addProperty("ISOFFLINE",false);
                map.addProperty("ISEQCADD",true);
                map.addProperty("TOTALQTY",etEqcNum.getText().toString());
                map.addProperty("CUSTOMERCODE",customercode);
                List<EdcEntity.EdcSet> edcsetlist = body.getEDCSETLIST();
                edcsetlist.get(0).setEDCSETITEMLINELIST(edcSetBinAdapter.getData());
                map.add("EDCSETLIST",new JsonParser().parse(new Gson().toJson(edcsetlist)).getAsJsonArray());
                NetUtils.requestPostNet("CPC.CPCSAVEEDCDATA","TRANSFERMES",this,map,callBack);
            }
        });
    }



}